<template>
  <wd-col-picker
    v-model="modelValue"
    :columns="area"
    :column-change="columnChange"
    :display-format="displayFormat"
    align-left
    :placeholder="placeholder"
    @confirm="onConfirm"
  ></wd-col-picker>
</template>

<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from "vue";
import RegionAPI from "@/api/system/region";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  placeholder: {
    type: String,
    default: "请选择行政区划",
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const modelValue = ref(props.modelValue);
const area = ref([[]]);

watch(
  () => props.modelValue,
  (val) => {
    modelValue.value = val;
  }
);

watch(modelValue, (val) => {
  emit("update:modelValue", val);
});

onMounted(async () => {
  try {
    // 初始化加载省份
    const res = await RegionAPI.getOptions({ type: 0, areaCode: 0 });
    if (res && Array.isArray(res)) {
      area.value[0] = res.map((i) => ({ label: i?.name || "", value: i?.areaCode || 0 }));
    } else {
      area.value[0] = [];
    }
  } catch (error) {
    console.error("加载省份数据失败:", error);
    area.value[0] = [];
  }
});
// 格式化方法
const displayFormat = (selectedItems) => {
  if (!selectedItems || selectedItems.length === 0) {
    return "";
  }

  // 使用filter和map确保只处理有效的项目
  const validItems = selectedItems.filter((item) => item && item.label);
  if (validItems.length === 0) {
    return "";
  }

  return validItems.map((item) => item.label).join("-");
};
// wd-col-picker 异步联动
const columnChange = async ({ selectedIndex, selectedItem, resolve, finish }) => {
  const nextLevel = selectedIndex + 1;
  // 异步加载下一级
  if (!selectedItem || !selectedItem.value) {
    finish();
    return;
  }

  try {
    const res = await RegionAPI.getOptions({ type: nextLevel, areaCode: selectedItem.value });
    if (res && res.length) {
      resolve(res.map((i) => ({ label: i.name || "", value: i.areaCode })));
    } else {
      finish();
    }
  } catch (error) {
    console.error("加载区域数据失败:", error);
    finish();
  }
};

const onConfirm = ({ value, selectedItems }) => {
  // 确保selectedItems是数组
  const safeSelectedItems = Array.isArray(selectedItems) ? selectedItems : [];
  emit("confirm", {
    value: Array.isArray(value) ? value : [],
    selectedItems: safeSelectedItems,
  });
};
</script>

<style scoped>
/deep/.wd-col-picker__cell {
  padding-left: 0 !important;
  font-size: 0.8rem !important;
  background: transparent !important;
  padding: 0 !important;
}

/deep/.wd-col-picker__value {
  text-align: left !important;
}
</style>
